package com.jiot.plugin.xxljob;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.IPlugin;
import com.xxl.job.core.executor.XxlJobExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class xxlJobPlugin implements IPlugin{
	private Logger logger = LoggerFactory.getLogger(xxlJobPlugin.class);

	private Prop xxlJobProp;
	private XxlJobExecutor xxlJobExecutor = null;
	
	public xxlJobPlugin(String configFile) {
		xxlJobProp = PropKit.use(configFile);
	}
	
	private void initXxlJobExecutor() {

		// registry jobhandler
		XxlJobExecutor.registJobHandler("demoJobHandler", new DemoJobHandler());
		XxlJobExecutor.registJobHandler("shardingJobHandler", new ShardingJobHandler());
		XxlJobExecutor.registJobHandler("httpJobHandler", new HttpJobHandler());
		XxlJobExecutor.registJobHandler("commandJobHandler", new CommandJobHandler());

		// init executor
		xxlJobExecutor = new XxlJobExecutor();
		xxlJobExecutor.setAdminAddresses(xxlJobProp.get("xxl.job.admin.addresses"));
		xxlJobExecutor.setAccessToken(xxlJobProp.get("xxl.job.accessToken"));
		xxlJobExecutor.setAddress(xxlJobProp.get("xxl.job.executor.address"));
		xxlJobExecutor.setAppname(xxlJobProp.get("xxl.job.executor.appname"));
		xxlJobExecutor.setIp(xxlJobProp.get("xxl.job.executor.ip"));
		xxlJobExecutor.setPort(xxlJobProp.getInt("xxl.job.executor.port"));

		xxlJobExecutor.setLogPath(xxlJobProp.get("xxl.job.executor.logpath"));
		xxlJobExecutor.setLogRetentionDays(xxlJobProp.getInt("xxl.job.executor.logretentiondays"));

		
	}
	
	@Override
	public boolean start() {
		initXxlJobExecutor();
		try {
			xxlJobExecutor.start();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return true;
	}
	
	@Override
	public boolean stop() {
		if (xxlJobExecutor != null) {
			xxlJobExecutor.destroy();
		}
		return false;
	}


}
